package com.dau.system.config.jwt;

import com.dau.common.annotation.CurrentUser;
import com.dau.entity.system.user.SysUser;
import com.dau.entity.system.user.UserProfile;
import com.dau.service.system.user.SysUserService;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@CurrentUser注解的方法参数，注入当前登录用户
 */
@Component
public class CurrentUserResolver implements HandlerMethodArgumentResolver {
    @Resource
    private SysUserService userInfoService;

    /**
     * 个人理解定义解析后返回的类 和需要解析的注解
     *
     * @param parameter 参数
     * @return boolean
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(SysUser.class) && parameter.hasParameterAnnotation(CurrentUser.class);

    }

    /**
     * 解析后返回的值
     *
     * @return {@link Object }
     */
    @Override
    public Object resolveArgument(@NonNull MethodParameter parameter, ModelAndViewContainer mavContainer,@NonNull  NativeWebRequest request, WebDataBinderFactory binderFactory) {
        //获取用户ID
        Object object = SecurityUtils.getSubject().getPrincipal();
        if (object == null) {
            return null;
        }
        //获取用户信息
        return userInfoService.getById(((UserProfile) object).getUserId());
    }
}
